<template>
  <div class="app-container">
    <SearchWithOperate
      :form-options="formOptions"
      btn-items="add,delete,export"
      @onSearch="handleQuery"
      @onAdd="handleAdd"
      @onReset="resetQuery"
      @onDelete="handleDeleteAll"
      @onExport="handleExport"
    >
      <template v-slot:dateRange>
        <el-date-picker
          v-model="dateRange"
          style="width: 200px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        />
      </template>
      <template v-slot:otherBtn>
        <el-button
          v-hasPermi="['system:dict:remove']"
          class="operate"
          type="primary"
          plain
          icon="iconfont icon-tool-refresh"
          @click="handleRefreshCache"
        />
      </template>
    </SearchWithOperate>

    <el-table
      v-loading="loading"
      tooltip-effect="light"
      :data="typeList"
      border
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" :selectable="selectable" />
      <el-table-column label="字典编号" prop="dictId" width="100">
        <template slot-scope="scope">
          <span>{{ (pageNum - 1) * pageSize + scope.$index + 1 }}</span>
        </template>
      </el-table-column>
      <el-table-column label="字典名称" prop="dictName" show-overflow-tooltip />
      <el-table-column label="字典类型" show-overflow-tooltip>
        <template slot-scope="scope">
          <span class="show-data" @click="showData(scope.row)">{{ scope.row.dictType }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" width="70">
        <template slot-scope="scope">
          <span class="stateShell">
            <div v-if="scope.row.status==='0'" class="common-prompt" style="background-color:#67C23A" />
            <div v-else class="common-prompt" style="background-color:#F56C6C" />
            <dict-tag :options="dict.type.status" :value="scope.row.status" />
          </span></template>
      </el-table-column>
      <el-table-column label="备注" prop="remark" show-overflow-tooltip />
      <el-table-column label="创建时间" align="center" width="180" prop="createTime">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.createTime) }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" width="180" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['system:dict:edit']"
            size="mini"
            type="primary"
            plain
            style="margin-right: 10px"
            @click="handleUpdate(scope.row)"
          >编辑</el-button>

          <el-button
            v-hasPermi="['system:dict:remove']"
            size="mini"
            type="danger"
            plain
            style="margin-right: 10px"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="字典名称" prop="dictName">
          <el-input v-model="form.dictName" placeholder="请输入字典名称" />
        </el-form-item>
        <el-form-item label="字典类型" prop="dictType">
          <el-input v-model="form.dictType" placeholder="请输入字典类型" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{ dict.label }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="submitLoading" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <Data ref="dictData" @ok="handleQuery" />
  </div>
</template>

<script>
import { listType, getType, delType, addType, updateType, refreshCache, changeDictStatus } from '@/api/system/dict/type'
import Data from './Data'
export default {
  name: 'Dict',
  dicts: ['sys_normal_disable', 'status'],
  components: { Data },
  data() {
    return {
      inherDicts: [],
      // 遮罩层
      loading: true,
      submitLoading: false,
      // 选中数组
      ids: [],
      names: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 总条数
      total: 0,
      // 字典表格数据
      typeList: [],
      pageNum: 1,
      pageSize: 10,
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 日期范围
      dateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        dictName: undefined,
        dictType: undefined,
        status: undefined
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        dictName: [
          { required: true, message: '字典名称不能为空', trigger: 'blur' }
        ],
        dictType: [
          { required: true, message: '字典类型不能为空', trigger: 'blur' }
        ],
        remark: [
          { max: 500, message: '最多可以输入500个字符', trigger: 'change' }
        ]
      },
      // 查询条件
      formOptions: [{
        label: '字典名称:',
        prop: 'dictName',
        type: 'input',
        placeholder: '请输入字典名称'
      }, {
        label: '字典类型:',
        prop: 'dictType',
        type: 'input',
        placeholder: '请输入字典类型'
      }, {
        label: '状态:',
        prop: 'status',
        type: 'select',
        options: [],
        placeholder: '字典状态'
      }, {
        label: '创建时间:',
        prop: 'dateRange',
        type: 'slot'
      }]
    }
  },
  created() {
    this.getList()
  },
  mounted() {
    this.formOptions[2].options = this.dict.type.sys_normal_disable
  },
  methods: {
    selectable(row, index) {
      if (!row.inherDict) {
        return true
      }
    },
    /** 查询字典类型列表 */
    getList() {
      this.loading = true
      listType(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.typeList = response.rows
        this.total = response.total
        this.loading = false
      }
      )
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        dictId: undefined,
        dictName: undefined,
        dictType: undefined,
        status: '0',
        remark: undefined
      }
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery(data) {
      this.queryParams = Object.assign(this.queryParams, data)
      this.queryParams.pageNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.submitLoading = false
      this.open = true
      this.title = '添加字典类型'
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.dictId)
      this.names = selection.map(item => item.dictName)
      this.inherDicts = selection.map(item => item.inherDict)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      if (row.inherDict) {
        this.$message.error('固有字典禁止修改!')
      } else {
        this.reset()
        this.submitLoading = false
        const dictId = row.dictId || this.ids
        getType(dictId).then(response => {
          this.form = response.data
          this.open = true
          this.title = '修改字典类型'
        })
      }
    },
    showData(row) {
      this.$refs.dictData.show(row.dictId, row.inherDict)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.submitLoading = true
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.dictId !== null && this.form.dictId !== undefined) {
            updateType(this.form).then(response => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            }).catch(err => {
              this.submitLoading = false
              console.error(err)
            })
          } else {
            addType(this.form).then(response => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            }).catch(err => {
              this.submitLoading = false
              console.error(err)
            })
          }
        } else {
          this.submitLoading = false
        }
      })
    },
    /** 批量删除 */
    handleDeleteAll() {
      if (this.inherDicts.find(item => item === true)) {
        this.$message.error('选中数据中包含固有字典！固有字典禁止删除')
      } else {
        if (this.ids.length > 0) {
          this.$modal.confirm('是否确认删除字典名称为"' + this.names + '"的数据项？').then(() => {
            return delType(this.ids).then(() => {
              this.getList()
              this.$modal.msgSuccess('删除成功')
            })
          }).catch(() => {})
        } else {
          this.$message.warning('未选中数据')
        }
      }
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      if (row.inherDict) {
        this.$message.error('固有字典禁止删除!')
      } else {
        this.$modal.confirm('是否确认删除字典名称为"' + row.dictName + '"的数据项？').then(function() {
          return delType(row.dictId)
        }).then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        }).catch(() => {})
      }
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('system/dict/type/export', {
        ...this.queryParams
      }, `type_${new Date().getTime()}.xlsx`)
    },
    /** 刷新缓存按钮操作 */
    handleRefreshCache() {
      refreshCache().then(() => {
        this.$modal.msgSuccess('刷新成功')
      })
    },
    /** 修改菜单状态*/
    handleStatusChange(row) {
      const text = row.status === '0' ? '启用' : '停用'
      this.$modal.confirm('确认要"' + text + '""' + row.dictName + '"菜单吗？').then(function() {
        return changeDictStatus(row.dictId, row.status)
      }).then(() => {
        this.$modal.msgSuccess(text + '成功')
      }).catch(function() {
        row.status = row.status === '0' ? '1' : '0'
      })
    }
  }
}
</script>
<style lang="scss" scoped>
.show-data {
  text-decoration:underline;
  cursor:pointer;
  color: #1890ff;
}
</style>
